<?php


namespace common\helpers;


use yii\db\Exception;

class DBManager
{
    public $dbHost = '';
    public $dbUser = '';
    public $dbPassword = '';
    public $dbSchema = '';
    public $pdo = null;

    public function __construct($host, $user, $password, $schema)
    {
        $this->dbHost = $host;
        $this->dbUser = $user;
        $this->dbPassword = $password;
        $this->dbSchema = $schema;
    }

    /**
     * 初始化连接
     * @throws Exception
     */
    public function initDb()
    {
        try {
            $pdo = new \PDO("mysql:dbname={$this->dbSchema};host={$this->dbHost}", $this->dbUser, $this->dbPassword);
        } catch (\PDOException $e) {
            throw new Exception('数据库连接失败' . $e->getMessage());
        }
        $this->pdo = $pdo;
    }

    /**
     * 判断数据库是否存在表
     * @return bool
     * @throws Exception
     */
    public function tableExists()
    {
        if (!$this->pdo) {
            $this->initDb();
        }
        $result = $this->pdo->query("SHOW TABLES FROM {$this->dbSchema}");
        $row = $result->fetchAll();
        if (!empty($row)) {
            throw new Exception('数据库中数据表已经存在');
        }
        return true;
    }

    public function splitSql($sql)
    {
        $sql = trim($sql);
        $sql = str_replace("\r\n", "\n", $sql);

        $buffer = array();
        $ret = array();
        $in_string = false;
        for ($i = 0; $i < strlen($sql) - 1; $i++) {
            if ($sql[$i] == ";" && !$in_string) {
                $ret[] = substr($sql, 0, $i);
                $sql = substr($sql, $i + 1);
                $i = 0;
            }
            if ($in_string && ($sql[$i] == $in_string) && $buffer[1] != "\\") {
                $in_string = false;
            } elseif (!$in_string && ($sql[$i] == '"' || $sql[$i] == "'") && (!isset($buffer[0]) || $buffer[0] != "\\")) {
                $in_string = $sql[$i];
            }
            if (isset($buffer[1])) {
                $buffer[0] = $buffer[1];
            }
            $buffer[1] = $sql[$i];
        }
        if (!empty($sql)) {
            $ret[] = $sql;
        }
        return ($ret);
    }

    /**
     * 执行sql
     * @param $DBPrefix
     * @param $file
     * @return bool
     * @throws Exception
     */
    public function populate_db($DBPrefix,$file)
    {
        if (!$this->pdo) {
            $this->initDb();
        }
        $query = fread(fopen($file, "r"), filesize($file));
        $pieces  = $this->splitSql($query);
        for ($i=0; $i<count($pieces); $i++) {
            $pieces[$i] = trim($pieces[$i]);
            if(!empty($pieces[$i]) && $pieces[$i] != "#") {
                $pieces[$i] = str_replace( "#__", $DBPrefix, $pieces[$i]);
                if (!$result = $this->pdo->query($pieces[$i])) {
                    throw new Exception('错误！!!');
                }
            }
        }
        return true;
    }

    public function initAccount($username,$password,$DBPrefix)
    {
        if (!$this->pdo) {
            $this->initDb();
        }
        $time = date('Y-m-d H:i:s');
        $password = \Yii::$app->security->generatePasswordHash($password);
        $sql = "INSERT INTO `{$DBPrefix}admin` (`id`,`username`, `password`, `realname`, `status`, `note`, `create_time`, `update_time`, `last_time`, `last_ip`, `avatar`) VALUES (1,'{$username}', '{$password}', '超管', '1', '超级管理员', '{$time}', '{$time}', '{$time}', '', '/public/static/admin/images/profile.jpg');";
        if (!$result = $this->pdo->query($sql)) {
            throw new Exception('错误！');
        }
        return true;
    }
}